package Uploadedto;

use HTTP::Request::Common qw(POST);
use HTTP::Cookies;
use LWP::UserAgent;
use URI::Escape;
use WWW::Mechanize;

sub upload
{   
    my $local_file = shift;
    my $hoster_config = shift;

	my $cookie_jar = HTTP::Cookies->new(
	    file => $::spreader_cookie_dir."uploadedto.dat",
	    autosave => 1,
	 );
	
	my $mech = WWW::Mechanize->new();
	my $browser = LWP::UserAgent->new();

	$mech->cookie_jar($cookie_jar);
	$browser->cookie_jar($cookie_jar);
	
	my $tmp = $mech->get("http://www.uploaded.to/home");
	
	if($tmp->content =~ /name=\"email\"/g)
	{
		$mech->form_number(1);
		$mech->field("email" => $hoster_config->{'username'});
		$mech->field("password" => $hoster_config->{'password'});
		$mech->submit();
	}

	$textbox_content =  "ftp://".$::spreader_ftp_user.":".$::spreader_ftp_pwd."\@".$::spreader_ftp_ip.$::spreader_ftp_path.$local_file."\n";

	my $try_again = 1;
	my $ini = 0;
	
	while($try_again)
	{
		my $response = $browser->get('http://uploaded.to/api/uploadserver');
		my $upload_server = $response->decoded_content;
		
		print "Versuche es mit folgendem Server: ". $upload_server . "\n";
		
		print "Der Remotelink lautet: ".$textbox_content."\n";
		
		my $response = HTTP::Request->new(POST => $upload_server.'remote?upload_id=1232142');
		#my $response = HTTP::Request->new(POST => 'http://s41b0-cb.uploaded.to/remote?upload_id=1232142');
		$response->content("bla=".uri_escape($textbox_content));
		
		$html = $browser->request($response)->as_string;
		
		unless($html =~ /error/ && !($html =~ /redir/))
		{
			#print "\n\n\n\n\n";
			#print $html;
			#print "\n\n\n\n\n";

            my $tmp = $mech->get('http://www.uploaded.to/uploads?output=links&ss=0&ssad=0&sf=0&sfad=0&sd=1&sdad=1&sds=0&sdsad=0&page=1&sff='.$local_file);
 
        	if($tmp->content =~ /$local_file/g)
        	{
                $try_again = 0;

				if($tmp->content =~ m!(^.*?/$local_file)!sg)
				{
					return $1;
				}
            }
			else
			{
				if($ini < 3)
    			{
    				$ini++;
    			}
    			else
    			{
    				return "FEHLER BEIM UPLOAD DER DATEI ". $local_file;
    			}
			}
		}
		else
		{		
			#print "\n\n\n\n\n";
			#print $html;
			#print "\n\n\n\n\n";

			print $upload_server." ist Ausgelastet, versuche anderen Server.\n";

			if($ini < 3)
			{
				$ini++;
			}
			else
			{
				return "FEHLER BEIM UPLOAD DER DATEI ". $local_file;
			}
		}
	}	
}

1;